<template>
  <div class="zy-content">
    <search
        :columns="searchData"
        @getSearch="getSearch(arguments)"
        ref="search"
    ></search>
    <div class="alarmConfiguration">
      <!-- 选中区域-->
      <div class="list-layout mt16" v-if="selection.length !== 0">
        <div class="btns clear">
          <span class="title">选中区域</span>
          <Button v-has="'planLink'" @click="assGroup(1)">关联同组订单</Button>
          <Button v-has="'cancellationplanLink'" @click="assGroup(2)"
          >取消关联同组订单
          </Button
          >
        </div>
        <!-- 表格 -->
        <div class="tableContent">
          <Table
              class="resizable-table"
              border
              size="small"
              highlight-row
              @on-current-change="rowClick"
              @on-column-width-resize="onColumnWidthResize"
              :columns="columns"
              ellipsis
              ref="selection"
              stripe
              :data="selection"
          >
            <template slot-scope="{ row, index }" slot="action">
              <span class="operationBtn" @click="deleteToSelection(row, index)"
              >移除</span
              >
            </template>
          </Table>
        </div>
      </div>
      <!-- 生产订单-->
      <div class="list-layout mt16">
        <!-- 批量删除 批量导出  批量导入 下载模板 新增-->
        <div class="btns clear">
          <span class="title">生产订单</span>
          <Button  v-has="'ExportTemplate'" @click="exportTemplateClick">导出</Button>
          <Button v-has="'planCase'" @click="closeCase(true)">结案</Button>
          <Button v-has="'Cancelclosure'" @click="closeCase(false)"
          >取消结案
          </Button
          >
          <Button v-has="'CuttingCancelclosure'" @click="closeCaseSap()"
          >物料过账
          </Button
          >
        </div>
        <!-- 表格 -->
        <div class="tableContent">
          <Table
              class="resizable-table"
              border
              size="small"
              highlight-row
              @on-current-change="rowClick"
              @on-column-width-resize="onColumnWidthResize"
              :columns="columns"
              @on-selection-change="onSelectChange"
              ellipsis
              ref="selection"
              stripe
              :data="dataArr"
          >
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="addToSelection(row)"
              >加入选中区</span
              >
            </template>
          </Table>
        </div>
        <!-- 分页 -->
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="delIds.length"/>
          <Page
              :total="total"
              :page-size="pageSize"
              :page-size-opts="pageSizeOption"
              :current="pageNum"
              @on-change="changePageNum"
              @on-page-size-change="changePageSize"
              show-sizer
              show-total
          />
        </div>
      </div>
      <!-- 排产视图-->
      <div class="list-layout mt16">
        <span class="title">排产视图</span>
        <div class="echatone" id="workHour"></div>
      </div>
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">订单BOM</span>
        </div>
        <!-- 表格 -->
        <div class="tableContent">
          <!-- @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,'planBom')}" -->
          <Table
              class="resizable-table"
              border
              ref="selection"
              @on-column-width-resize="onColumnWidthResize"
              size="small"
              :columns="columnsK"
              ellipsis
              stripe
              :data="dataArr2"
          >
            <template slot-scope="{ row }" slot="action">
              <span
                  v-if="row.isSync == '否'"
                  class="operationBtn"
                  @click="createfaultCodeShowH(row)"
              ><i class="iconfont zy-common-bianji"></i>
                {{ $t("common.Edit") }}
              </span>
              <span
                  v-if="row.isSync == '否'"
                  class="operationBtn"
                  @click="delPrrShowH(row)"
              >
                <i class="iconfont zy-common-shanchu"></i>
                {{ $t("common.Delete") }}
              </span>
            </template>
          </Table>
        </div>
        <div class="pageWrap mt16">
          <Page
              :total="total2"
              :page-size="pageSize2"
              :page-size-opts="pageSizeOption"
              :current="pageNum2"
              @on-change="changePageNum2"
              @on-page-size-change="changePageSize2"
              show-sizer
              show-total
          />
        </div>
      </div>


      <!-- 结案原因选择弹窗 -->
      <Modal
          :mask-closable="false"
          v-model="showEndReasonModal"
          title="选择结案原因"
          width="400"
      >
        <div style="display: flex;"> 订单号：
          <div v-for="(item,index) of sumForm" :key="index">
            {{ item.AUFNR }} <span v-if="index<sumForm.length-1">,</span>
          </div>
          未完成，请输入结案原因
        </div>

        <Form label-position="top" style="margin-top: 20px">
          <FormItem label="结案原因" prop="endReason">
            <Select v-model="selectedEndReason" filterable>
              <Option
                  v-for="item in endReasonList"
                  :value="item.id"
                  :key="item.id"
              >{{ item.context }}
              </Option>
            </Select>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button @click="showEndReasonModal = false">取消</Button>
          <Button type="primary" @click="confirmEndReason">确定</Button>
        </div>
      </Modal>

      <!-- 新增编辑 -->
      <Modal
          :mask-closable="false"
          v-model="create"
          :title="addtitle"
          class="modal-content-layout"
          width="30%"
      >
        <div class="content-item">
          <Form class="search-form" ref="bomForm" label-position="top">
            <FormItem label="需求用量" class="item">
              <Input
                  type="text"
                  v-model="editData.needQuantity"
                  @on-keyup="keyUp($event, 'needQuantity', true)"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
              ></Input>
            </FormItem>
          </Form>
        </div>
        <div slot="footer">
          <Button type="default" @click="create = false">{{
              $t("common.Cancle")
            }}
          </Button>
          <Button type="primary" :loading="loading" @click="addOk">{{
              $t("maintenance.Confirmed")
            }}
          </Button>
        </div>
      </Modal>
      <!-- 请确认是否删除弹框 -->
      <Modal
          :mask-closable="false"
          v-model="delFaultCodeShowF"
          :title="$t('common.Delete')"
          class="modal-title-layout"
      >
        <div class="icon red">
          <i class="iconfont zy-common-shanchu"></i>
        </div>
        <p class="title">
          <span>{{ $t("common.confirmDelete") }}</span>
        </p>
        <div slot="footer">
          <Button type="default" @click="delFaultCodeShowF = false">{{
              $t("common.Cancle")
            }}
          </Button>
          <Button type="primary" :loading="loading" @click="deleteOk">{{
              $t("maintenance.Confirmed")
            }}
          </Button>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  searchApi,
  associateGroup,
  cancelAssociateGroup,
} from "@/api/planManage/productionPlan.js";
import search from "@/components/curd/searchList.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
import fileDownload from "js-file-download";

let myChart;
export default {
  name: "productionPlan",
  components: {search},
  mixins: [toggleTableOperation],
  data() {
    return {
      showEndReasonModal: false, // 控制弹窗显示
      endReasonList: [],        // 结案原因列表
      selectedEndReason: null,  // 选中的结案原因ID
      currentRow: null,
      delIds: [],
      searchData: [
        {
          title: "作业工序",
          key: "productionProcesses",
        },
        {
          title: "订单号",
          key: "orderCode",
        },
        {
          title: "车间",
          key: "workShop",
        },
        {
          title: "订单组号",
          key: "workOrderGroup",
          type: "search",
          dicUrl: "/dms/productionOrder/groupList",
          queryName: "value",
          resultParams: "res.data",
          params: {
            label: "workOrderGroup",
            value: "workOrderGroup",
          },
        },
        {
          title: "状态",
          key: "stateList",
          type: "select",
          multiple: true,
          maxTagCount: 1,
          dicData: [
            {label: "待排产", value: "待排产"},
            {label: "完成", value: "完成"},
            {label: "已结案", value: "已结案"},
            {label: "已排产", value: "已排产"},
            {label: "取消结案", value: "取消结案"},
          ],
        },
        {
          title: "产品编码",
          key: "orderMaterialCode",
        },
        {
          title: "产品名称",
          key: "materialName",
        },
        {
          title: "创建时间",
          key: "time",
          format: 'yyyy-MM-dd',
          type: "daterange",
          defaultTimeRange: 30,
          noreset: true,
          clearable: false,
        },
        {
          title: "图号规格",
          key: "customMaterialCode",
        },
        {
          title: "MRP创建者",
          key: "mrpController",
        },
        {
          title: "销售订单号",
          key: "saleOrderCode",
        },
        {
          title: "备注1",
          key: "remarks1",
        },
        {
          title: "备注2",
          key: "remarks2",
        },
        {
          title: "是否物料过账",
          key: "isPassBill",
          type: "select",
          dicData: [
            {label: "是", value: "是"},
            {label: "否", value: "否"},
          ],
        },
        {
          title: '订单实际完成时间',
          key: 'time2',
          type: 'datetimerange',
          format: 'yyyy-MM-dd HH:mm:ss',
          span: 8,
        },
      ],
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          fixed: 'left',
          align: "center",
        },
        {
          title: "销售订单号",
          key: "saleOrderCode",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "销售订单行号",
          key: "saleOrderItem",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "订单号",
          key: "orderCode",
          minWidth: 90,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "工序",
          key: "productionProcesses",
          width: 90,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "订单组号",
          key: "workOrderGroup",
          width: 200,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "车间",
          key: "workShop",
          minWidth: 170,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "客户",
          key: "custom",
          width: 90,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "产品编号",
          key: "orderMaterialCode",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "产品名称",
          key: "materialName",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "产品型号",
          key: "materialModel",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "图号规格",
          key: "customMaterialCode",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "材料牌号",
          key: "materialMark",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划数量",
          key: "planQuantity",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },

        {
          title: "提报数量",
          key: "reportedQuantity",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "报废数",
          key: "outNumTotal",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "领料数",
          key: "operationQuantity",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "状态",
          key: "state",
          width: 90,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "是否物料过账",
          key: "isPassBill",
          width: 140,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划开始时间",
          key: "planStartDate",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划完成日期",
          key: "planFinishDate",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: '实际完成时间',
          key: 'orderFinishTime',
          width: 130,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划交期",
          key: "deliverDate",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },

        {
          title: "备注",
          key: "remarks",
          width: 90,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "MES创建时间",
          key: "createTime",
          width: 120,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "维护人",
          key: "createBy",
          width: 90,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "MRP创建者",
          key: "mrpController",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "备注1",
          key: "remarks1",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "备注2",
          key: "remarks2",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "备注3",
          key: "remarks3",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "备注4",
          key: "remarks4",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "备注5",
          key: "remarks5",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "油品分类",
          key: "oilClassification",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "客户牌号",
          key: "customMark",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },

        {
          title: "超报比例",
          key: "overreportingRatio",
          minWidth: 110,
          align: "center",
          resizable: true,
          tooltip: true,
          render: (h, params) => {
            return h(
                "div", params.row.overreportingRatio ? params.row.overreportingRatio + "%" : ''
            );
          },
        },
        {
          title: `${this.$t("common.operation")}`,
          slot: "action",
          fixed: "right",
          minWidth: 160,
          align: "center",
        },
      ],
      columnsK: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center",
        },
        {
          title: "物料编号",
          key: "materialCode",
          width: 120,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "物料名称",
          key: "materialName",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "物料类别",
          key: "materialType",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "需求数量",
          key: "needQuantity",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计量单位",
          key: "unit",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "材料牌号",
          key: "materialMark",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          //title: '操作',
          title: `${this.$t("common.operation")}`,
          slot: "action",
          fixed: "right",
          minWidth: 160,
          align: "center",
        },
      ],
      allCheck: false,
      loading: false,
      create: false,
      searchParams: {},

      pageNum: 1,
      pageSize: 10,
      total: 0,
      dataArr: [],
      sumForm: {},
      pageNum2: 1,
      pageSize2: 10,
      total2: 0,
      dataArr2: [],

      delFaultCodeShowF: false, //是否显示删除弹窗
      pageSizeOption: [2, 5, 10, 20],
      selection: [],
      closeList: [],
      editData: {},
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    // this.getTableColumnsWidth(this.columnsK,'planBom');
    this.$refs.search.getSearch()
  },
  methods: {
    onSelectChange(selection) {
      let myArray = [];

      selection.map((item) => {
        myArray.push(item);
      });
      this.delIds = myArray;
    },
    keyUp(e, key, money) {
      // 如果是删除为空 则不处理
      if (!this.editData[key]) {
        return (this.editData[key] = "");
      }
      // 每次抬键处理,对应金额渲染两位小数||数字
      let num = "";
      if (money) {
        num = this.editData[key].match(/^\d*(\.?\d{0,2})/g)[0];
      } else {
        num = this.editData[key].replace(/^[^\d]+$/g, "").split(".")[0];
      }
      this.editData[key] = `${num}`;
    },
    delPrrShowH(row) {
      this.delFaultCodeShowF = true;
      this.editData.id = row.id;
    },
    addToSelection(row) {
      const has = this.selection.find((item) => item.id === row.id);
      if (has) {
        this.$Message.warning({
          content: "记录已加入选中区",
          duration: 6,
          closable: true,
        });
        return;
      }
      this.selection.push(row);
    },
    deleteToSelection(row, index) {
      this.selection.splice(index, 1);
    },
    getSearch(params) {
      this.searchParams = JSON.parse(JSON.stringify(params[0])) || {};
      const {time, time2} = this.searchParams;
      if (time && time.length == 2) {
        this.searchParams.startTime = this.searchParams.time[0];
        this.searchParams.endTime = this.searchParams.time[1];
        delete this.searchParams.time;
      }
      if (time2 && time2.length == 2) {
        this.searchParams.orderFinishTimeStart = this.searchParams.time2[0];
        this.searchParams.orderFinishTimeEnd = this.searchParams.time2[1];
        delete this.searchParams.time2;
      }
      this.pageNum = 1;
      this.searchList();
    },
    changeNum(data) {
      this.pageNum = 1;
      this.searchParams = data;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    changeNum2() {
      this.pageNum2 = 1;
      this.getAnalyse();
    },
    changePageSize2(pageSize) {
      this.pageSize2 = pageSize;
      this.getAnalyse();
    },
    changePageNum2(val) {
      this.pageNum2 = val;
      this.getAnalyse();
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      searchApi(params).then((res) => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    deleteOk() {
      this.loading = true;
      this.axios({
        url: "/dms/productionOrderMaterial/delete",
        method: "delete",
        data: [this.editData.id],
      }).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.getAnalyse();
          this.$Message.success("删除成功");
          this.delFaultCodeShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    addOk(name) {
      if (!this.editData.needQuantity) {
        this.$Message.warning({
          content: "请输入需求数量",
          duration: 6,
          closable: true,
        });
        return;
      }
      this.axios({
        url: "/dms/productionOrderMaterial/updateNeedQuantity",
        method: "put",
        data: {
          ...this.editData,
        },
      }).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.getAnalyse();
          this.$Message.success("编辑成功");
          this.create = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    createfaultCodeShowH(row) {
      //点击增加或编辑
      this.addtitle = `${this.$t("common.Edit")}`;
      this.editData = {
        id: row.id,
        needQuantity: row.needQuantity,
      };
      this.create = true;
    },
    reData(persent, value) {
      console.log(persent, valueList);
      let valueList = JSON.parse(JSON.stringify(value));
      for (let i = 0; i < valueList.length; i++) {
        const oneLine = valueList[i].values;

        for (let j = 0; j < oneLine.length; j++) {
          oneLine[j].realyValue = oneLine[j].value;
          oneLine[j].value = persent[j][i];
        }
      }
      return valueList;
    },
    getValuePersent(arr) {
      let res = {};
      for (let i in arr) {
        const sum = arr[i].reduce((acc, val) => acc + val, 0);
        const result = arr[i].map((val) => {
          // console.log(val, sum);
          return (val / sum) * 100;
        });
        res[i] = result;
      }
      return res;
    },
    // 将横向转为竖向数组{0:<index>:[value],1:[],2:[]}
    getOneNum(valueList) {
      let res = {};
      // 获取数据在各自列中小数占比*100 key=value
      for (let i = 0; i < valueList.length; i++) {
        let values = valueList[i].values;
        for (let j = 0; j < values.length; j++) {
          const element = values[j];
          if (j in res) {
            res[j].push(element.value);
          } else {
            res[j] = [];
            res[j].push(element.value);
          }
        }
      }
      return res;
    },
    getAnalyse(row) {
      this.axios({
        method: "get",
        url: "/dms/productionWork/inventoryAnalysis",
        params: {
          orderCode: this.currentRow.orderCode,
          pageNum: this.pageNum2,
          pageSize: this.pageSize2,
        },
      }).then((res) => {
        if (res.code === 200) {
          this.dataArr2 = res.data.records || [];
          this.total2 = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    rowClick(row) {
      this.currentRow = JSON.parse(JSON.stringify(row));
      this.changeNum2();
      const that = this;
      this.axios({
        method: "get",
        url: "/dms/productionWork/productView",
        params: {
          orderCode: row.orderCode,
        },
      }).then((res) => {
        if (res.code === 200) {
          const data = res.data || {valueList: [], workShop: []};
          const valueList = data.valueList || [];
          const workShop = data.workShop || [];

          that.oneNum = that.getOneNum(valueList);
          let persent = that.getValuePersent(that.oneNum);
          const redata = that.reData(persent, valueList);

          const series = redata.map((item) => {
            return {
              name: item.state || "",
              type: "bar",
              stack: "total",
              label: {
                show: true,
                formatter: (params) =>
                    params.value == 0 || params.value == 100
                        ? params.value + "%"
                        : params.value.toFixed(2) + "%",
              },
              data: item.values || [],
            };
          });
          this.initEchart(workShop, series);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    //查询列表
    searchList1() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      searchApi(params).then((res) => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    closeCase(type) {
      if (this.delIds.length == 0) {
        this.$Message.warning({
          content: "至少选中一条数据",
          duration: 6,
          closable: true,
        });
        return;
      }
      const data = this.delIds.map((item) => {
        return {
          AUFNR: item.orderCode,
          WERKS: item.factory,
        };
      });
      this.axios({
        method: "post",
        url: type
            ? "/dms/apiMethod/closeCase"
            : "/dms/apiMethod/cancelCloseCase",
        data,
      }).then((res) => {
        if (res.code === 200) {
          this.$Message.success({
            content: res.msg,
            duration: 6,
            closable: true,
          });
          this.searchList();
        } else if (type && res.code == 4007) {
          this.sumForm = res.data
          // AUFNR
          this.fetchEndReasons()
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    fetchEndReasons() {
      this.axios({
        method: "post",
        url: "/dms/basicEndReasons/list",
        data: {status: 1, pageNo: 1, pageSize: 999999} // 只查询启用的原因
      }).then(res => {
        if (res.code === 200) {
          this.endReasonList = res.data.list || [];
          this.showEndReasonModal = true;
        } else {
          this.$Message.warning(res.msg);
        }
      });
    },
    confirmEndReason() {
      if (!this.selectedEndReason) {
        this.$Message.warning("请选择结案原因");
        return;
      }

      const postData = this.delIds.map(item => ({
        AUFNR: item.orderCode,
        WERKS: item.factory,
        endReasonsId: this.selectedEndReason // 添加结案原因ID
      }));

      this.axios({
        method: "post",
        url: "/dms/apiMethod/closeCase",
        data: postData
      }).then(res => {
        this.showEndReasonModal = false;
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.searchList();
        } else {
          this.$Message.warning(res.msg);
        }
      });
    },
    closeCaseSap() {
      if (this.delIds.length == 0) {
        this.$Message.warning({
          content: "至少选择一条数据",
          duration: 6,
          closable: true,
        });
        return;
      }
      const data = this.delIds.map((item) => {
        return {
          AUFNR: item.orderCode,
          WERKS: item.factory,
        };
      });
      this.axios({
        method: "post",
        url: "/dms/apiMethod/closeCaseSap",
        data,
      }).then((res) => {

        this.$Message.success({
          content: res.msg,
          duration: 6,
          closable: true,
        });
      });
    },
    assGroup(status) {
      const len = this.selection.length;
      if (status == 2) {
        if (this.selection.length < 1) {
          this.$Message.error({
            content: "请选择一条数据",
            duration: 6,
            closable: true,
          });
          return;
        }
      } else if (len < 2) {
        this.$Message.error({
          content: "请选择两条以上的数据",
          duration: 6,
          closable: true,
        });
        return;
      }
      const ids = this.selection.map((item) => item.id);
      if (status == 1) {
        associateGroup(ids).then((res) => {
          if (res.code === 200) {
            this.$Message.success({
              content: res.msg,
              duration: 6,
              closable: true,
            });
            this.searchList();
            this.selection = [];
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        });
      } else {
        cancelAssociateGroup(ids).then((res) => {
          if (res.code === 200) {
            this.$Message.success({
              content: res.msg,
              duration: 6,
              closable: true,
            });
            this.searchList();
            this.selection = [];
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        });
      }
    },
    initEchart(workShop, series) {
      if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose(); //销毁
      }
      myChart = echarts.init(document.getElementById("workHour"));
      myChart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // Use axis to trigger tooltip
            type: "line", // 'shadow' as default; can also be 'line' or 'shadow'
          },
        },
        tooltip: {
          position: "top",
          triggerOn: "mousemove",
          formatter: function (params) {
            return params.data.value.toFixed(2) + "%";
          },
        },
        legend: {},
        grid: {
          top: "13%",
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: workShop,
          axisLabel: {},
        },
        yAxis: {
          type: "value",
          axisLabel: {
            show: true,
            interval: "auto",
            formatter: "{value} %",
          },
          show: true,
        },
        series,
      });
      myChart.lastBandWidth = 0;
      // 监听渲染事件，只要bandWidth发生变化，重新设置标签偏移的值
      myChart.on("rendered", function () {
        let bandWidth =
            myChart._chartsViews[0].renderTask.context.outputData._layout
                .bandWidth;
        if (myChart.lastBandWidth != bandWidth) {
          myChart.lastBandWidth = bandWidth;
          // 延时执行否则echarts渲染异常
          setTimeout(() => {
            // 加上偏移后重新绘制
            let optionNew = {xAxis: [{}, {}]};
            // 增量更新偏移值
            optionNew.xAxis[1] = {
              axisLabel: {rich: {offset: {width: myChart.lastBandWidth}}},
            };
            //console.info(optionNew);
            myChart.setOption(optionNew);
          }, 0);
        }
      });
      window.addEventListener("resize", function () {
        myChart.resize(); //myChart指自己定义的echartsDom对象
      });
    },
    handleChange(val) {
      this.companyName = val ? val.label : "";
    },
    handleType(val) {
      if (val === 1) {
        this.dateTimeRange = [
          this.$moment(new Date()).subtract(1, "year").format("YYYY-MM-DD"),
          this.$moment(new Date()).format("YYYY-MM-DD"),
        ];
      } else {
        this.dateTimeRange = [
          this.$moment(new Date()).subtract(7, "days").format("YYYY-MM-DD"),
          this.$moment(new Date()).format("YYYY-MM-DD"),
        ];
      }
    },
    //日期
    handleChangeDate(val) {
      // console.log(val);
      this.dateTimeRange = val;
    },
    exportTemplateClick() {
      let params = {};
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      const filName = this.$t("生产订单报表");
      this.axios({
        url: "/dms/productionOrder/orderExport",
        method: "post",
        data: params,
      }).then((res) => {
        if (res.code == 1) {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        } else {
          this.axios({
            url: "/dms/productionOrder/orderExport",
            method: "post",
            responseType: "blob",
            data: params,
          }).then((res) => {
            fileDownload(res, filName + ".xlsx");
          });
        }
      });
    },
    getCompanyList() {
      this.axios({
        method: "get",
        url: "/basic/company/getCompanyListByUser",
        params: {},
      }).then((res) => {
        if (res.code === 200) {
          this.companyList = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.echatone {
  width: 100%;
  height: 320px;
  display: flex;

  .echattwo {
    height: 100%;
    width: 40%;
  }

  .echatthree {
    height: 100%;
    width: 60%;
  }
}
</style>
